/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
const table = 'SalesOrder';
const moment = require('moment');
const { getTax } = require('../base/serviceBase');
module.exports = class extends base {

  /**
   * {
   *   code: 'SAL251014113259',
   *   addMaterials: [],
   *   division: '镇江新蓝化工科技有限公司',
   *   lots: [],
   *   shippingFee: 0,
   *   customerCode: 'CUS251012004702',
   *   customer: '中兴通迅',
   *   prods: [
   *     {
   *       prodName: '品名2',
   *       prodCode: 'asdff',
   *       count: 300,
   *       price: 50,
   *       pkgFee: 0,
   *       laborFee: 0,
   *       taxDeductionPointForLaborCosts: 0,
   *       materials: [Array],
   *       fileList: [Array],
   *       pLotId: 'SPD1760413425175'
   *     }
   *   ],
   *   laborRatio: 0,
   *   amount: 15000,
   *   count: 300,
   *   projectType: '物资',
   *   mainCost: 50360,
   *   auxiliaryMaterialFee: 0,
   *   mgrFee: '1200.00',
   *   usedShippingFee: '00.00320.00',
   *   unloadFee: 0,
   *   tray: 0,
   *   publicFee: 0,
   *   pkgFee: 0,
   *   laborFee: 0,
   *   taxDeductionPointForLaborCosts: 0,
   *   taxRate: '13%',
   *   valueAddedTax: '-4067.96',
   *   addedTax: '-488.16',
   *   incomeTax: '-1540.39',
   *   stampDuty: '3.98',
   *   table: 'SalesOrder',
   *   reviewStatus: '待审核',
   *   tenantCode: 'TEN250429020943B7AB',
   *   createUser: 'admin',
   *   createUsername: 'admin',
   *   tenantName: '镇江蓝海化工',
   *   tax: '1725.66'
   * }
   *
   * used material
   *   {
   *     _id: 68ede3c83bc59b88809b09aa,
   *     isDeleted: false,
   *     reviewStatus: '待审核',
   *     inboundStatus: '待入库',
   *     acceptanceStatus: '待验收',
   *     useCount: 0,
   *     usedCount: 20,
   *     inboundCount: 0,
   *     outboundCount: 0,
   *     salesOrders: [],
   *     pmLotId: 'PML2025-10-14-13-46-47',
   *     code: 'MAT250702010209487D',
   *     name: '物料名称1',
   *     subcategory: '物料小类1',
   *     spec: '32*2323',
   *     type: '类别1',
   *     number: 'NUMBER1',
   *     createUser: 'admin',
   *     createUsername: 'admin',
   *     tenantCode: 'TEN250429020943B7AB',
   *     tenantName: '镇江蓝海化工',
   *     updatedTs: 2025-10-14T05:46:48.523Z,
   *     __v: 0,
   *     count: 20,
   *     price: 20,
   *     shippingFee: 800,
   *     target: '自用',
   *     procureOrderCode: 'PRO1760420808512',
   *     vendor: '四川上上',
   *     vendorCode: 'VEN250519085723BE6A',
   *     isRent: false,
   *     division: '镇江新蓝化工科技有限公司',
   *     createdTs: 2025-10-14T05:46:48.523Z,
   *     _useCount: 5
   *   }
   * @returns {Promise<{status: string, result: *}>}
   * @param material
   * @param tenantCode
   */
  async usedMaterial(material,tenantCode){
    const { ctx } = this;
    const { usedMaterialRecord } = material;
    _.map(usedMaterialRecord, async usedMaterialRecord => {
      const { _useCount, pmLotId } = usedMaterialRecord;
      const res1 = await ctx.app.dbs.updateOne('ProcureMaterialRecord', {
        pmLotId,
        tenantCode
      }, { $inc: { useCount: _useCount } });
      const res2 = await ctx.app.dbs.updateOne('Material', {
        code: material.code,
        tenantCode
      }, { $inc: { procureCount: -_useCount } });
    });
  }
  async create(body) {
    const { ctx, service } = this;
    const {
      code,
      tenantCode,
      tenantName,
      createUser,
      createUsername,
      customer,
      address,
      prods = [],
      contacts,
      contactsPhone,
      createdTs, amount, taxRate
    } = body;
    body.tax = this.getTax(amount, taxRate);

    let laborFeeTotal = 0;
    console.log('create sales order body', body);
    /**
     * 扣库存
     */
    //  const res = await this.createSalesProds(ctx, tenantCode, code, prods);

    /**
     * 占用采购物料批次
     */

    _.map(prods, async prod => {
      prod.salesOrderCode = code;
      prod.tenantCode = tenantCode;
      prod.customer = customer;
      const res1 = await ctx.app.dbs.insert('SalesProdRecord', prod);
      const { materials ,pkgMaterials} = prod;
      _.map(materials, async material => {
       const res=await this.usedMaterial(material,tenantCode)
      });
      _.map(pkgMaterials, async material => {
        const res=await this.usedMaterial(material,tenantCode)
      });
    });


    _.map(prods, async prod => {
      const { laborFee } = prod;
      laborFeeTotal += laborFee;
    });
    body.laborFeeTotal = laborFeeTotal;
    body.orderCode = code;
    const custom = await ctx.app.dbs.findOne('Customer', { tenantCode, name: customer });
    if (!custom) {
      const code = _stringUtils.getCode('CUS');
      body.customerCode = code;
      const custom = await ctx.app.dbs.insert('Customer', {
        code,
        name: customer,
        tenantCode,
        tenantName,
        createUser,
        createUsername,
        customer,
        address,
        contacts,
        contactList: !address && !contacts && !contactsPhone ? undefined : [ {
          address, contacts, contactsPhone,
          code: 'ADD' + Date.now()
            .valueOf()
        } ],
        createdTs
      });
    }
    // delete body.prods;
    const result = await ctx.app.dbs.insert('SalesOrder', body);

//    const result1 = await service['outboundService'].createOutboundOrder(body);
    const historyRes = await ctx.app.dbs.insert('History', {
      table,
      name: '新建订单',
      code,
      tenantCode,
      tenantName,
      createUser,
      createUsername,
      createdTs,
      newData: body
    });
    return { status: 'ok', result };
  }

  /**
   * 物料占用时，查找可用的采购物料批次
   * @param material
   * @returns {Promise<{status: string, result: *[]}>}
   */
  async findUsedMaterialRecord(material) {
    /**
     * 占用采购物料批次
     * 1、不需要检查物料是否有采购批次，在物料选择时已经检查过了
     * 2、检查最新的采购单物料，是否满足数量要求，如果满足，返回
     * 3、轮询物料采购记录，按订单数量进行占用
     */
    const { ctx } = this;
    let { tenantCode, code, materialCount, salesOrderCode } = material;
    console.log('find',materialCount);
    const _material = await ctx.app.dbs.findOne('Material', { tenantCode, code });
    // console.log('所有可用数量 code', tenantCode, code);
    // console.log('所有可用数量', _material);
    // if (!_material) {
    //   console.log('现有计划可用数量为0');
    //   throw new Error('现有计划可用数量为0');
    // }
    // if (materialCount > _material.procureCount) {
    //   console.log('订单数量大于现有计划可用数量');
    //   throw new Error('订单数量大于现有计划可用数量');
    // }

    const cache = {
      recordId: 'SUM' + moment()
        .format('YYYYMMDDHHmmss'),
      tenantCode,
      //salesOrderCode,
    };
    /**
     * 如果第一条数量大于订单数量
     */
    const res = await ctx.app.dbs.findOne('ProcureMaterialRecord', { tenantCode, code });
   // console.log('ProcureMaterialRecordd', res,tenantCode, code);
    if (res) {
      const { count = 0, useCount = 0, procureOrderCode, pmLotId } = res;
      if ((count - useCount) > materialCount) {
        console.log('第一条数量大于订单数量');
        cache.pmLotId = pmLotId;
        cache.procureOrderCode = procureOrderCode;
        cache.usedCount = materialCount;
        res._useCount = materialCount;
        //  const res = await ctx.app.dbs.insert('CacheProcureLotUsed', cache);
        return { status: 'ok', result: [ res ] };
      }
    }

    /**
     * 占用多个物料批次
     */
    const result = [];
    const list = await ctx.app.dbs.find('ProcureMaterialRecord', { tenantCode, code });
    _.map(list, record => {
      const { count, useCount, pmLotId, procureOrderCode } = record;
      const ucount = count - useCount;
      if (ucount > 0) {
        console.log('count数量：', count, 'useCount', useCount);
        const _count = count - useCount;//可用的数量
        console.log('需求数量：', materialCount, '可用数量', _count);
        materialCount -= _count;
        console.log('计算后数量：', _count, materialCount);
        if (materialCount > 0) {
          cache.pmLotId = pmLotId;
          cache.procureOrderCode = procureOrderCode;
          cache.useCount = _count;
          record._useCount = _count;
          //    const res = ctx.app.dbs.insert('CacheProcureLotUsed', cache);
          result.push(record);
        } else {
          cache.pmLotId = pmLotId;
          cache.procureOrderCode = procureOrderCode;
          cache.useCount = materialCount + _count;
          record._useCount = materialCount + _count;
          //  const res = ctx.app.dbs.insert('CacheProcureLotUsed', cache);
          result.push(record);
        }
      }
    });
    console.log(result);
    return { status: 'ok', result };
  }

  getValue = (_type, value, key) => {
    if (_type === 'date') {
      console.log('日期', value, key);
      if (key.includes('.')) {
        console.log('下一级日期，需要转换');
        return {
          $gte: moment(value[0])
            .startOf('day')
            .valueOf(),
          $lt: new moment(value[1])
            .endOf('day')
            .valueOf()
        };
      }

      // query[key]={$eq:new Date(moment(value).valueOf())}
      return {
        $gte: new Date(moment(value[0])
          .startOf('day')
          .valueOf()),
        $lt: new Date(moment(value[1])
          .endOf('day')
          .valueOf())
      };
    }
    if (_type === 'string' || _type === 'select') {
      if (typeof value === 'string') {
        return { $regex: value };
      } else {
        return value;
      }

    }
    if (_type === 'number') {
      const t = value.charAt(0);
      const number = value.substring(1);
      if (!this.isNumber(number)) {
        throw new Error(`数字查询条件错误：${key},${value} `);
      }
      const _number = parseFloat(number);
      if (t !== '<' && t !== '>' && t !== '=' && this.isNumber(number)) {
        return { $eq: _number };
      } else {
        if (t === '<') {
          return { $lt: _number };
        }
        if (t === '>') {
          return { $gt: _number };
        }
        if (t === '=') {
          return { $eq: _number };
        }
      }
    }
    return undefined;
  };

  async findMany(body) {
    const { ctx, service } = this;
    const { tenantCode } = body;
    const query = { tenantCode };
    const { prods = {}, isKP, isFH, createdTs } = body;
    const { materials = {} } = prods;
    delete body['tenantName'];
    delete body['tenantCode'];
    delete body['isDeleted'];
    delete body['prods'];
    delete body['materials'];
    delete body['createdTs'];

    const schema = await service.globalService.getModel({ table: 'SalesOrder' });
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });

    _.map(prods, (value, key) => {
      const temp = _.find(schema.prods, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        const _key = `prods.${key}`;
        query[_key] = this.getValue(_type, value, _key);
      }
    });

    _.map(materials, (value, key) => {
      const temp = _.find(schema.prods.materials, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        const _key = `prods.materials.${key}`;
        query[_key] = this.getValue(_type, value, _key);
      }
    });
    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    delete query['prods.materials'];
    if (isKP && isKP === '已开票') {
      query['prods.invoicingDate'] = { $ne: null };
    }
    if (isKP && isKP === '未开票') {
      query['prods.invoicingDate'] = { $eq: null };
    }
    if (isFH && isFH === '已发货') {
      query['outboundCount'] = { $gt: 0 };
    }
    if (isFH && isFH === '未发货') {
      query['outboundCount'] = { $eq: 0 };
    }
    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    console.log('find sales order query', query);
    const res = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    const res1 = [];
    _.map(res, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      res1.push(item);
    });

    const array = [];
    let amount = 0,
      count = 0;
    _.map(res1, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      amount += item.amount;
      count += item.count;
      array.push(item);
    });
    const result = { amount, count, array };
    return { status: 'ok', result };
  }

  async findOne(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.findOne(table, { tenantCode, code });
    // console.log('find sales order body', body);
    // result.prods = await ctx.app.dbs.find('SalesProdRecord', { tenantCode, salesOrderCode: code });
    console.log('查找 订单', result);
    return { status: 'ok', result };
  }

  async updateMaterials(body) {
    const {
      tenantCode,
      code,
      prods
    } = body;
    const { ctx, service } = this;
    const oldData = await ctx.app.dbs.findOne(table, { tenantCode, code });
    const oldMaterials = [];

    _.map(oldData.prods, (item) => {
      _.map(item.materials, (it, k) => {
        const { usedProcureMaterialLots } = it;
        oldMaterials.push(...usedProcureMaterialLots);
        console.log('mm', usedProcureMaterialLots);
      });
    });

    _.map(oldMaterials, async (item) => {
      const { materialCount, pmLotId } = item;
      console.log('mm1', pmLotId);
      const res1 = await ctx.app.dbs.updateOne('ProcureMaterialRecord', {
        pmLotId,
        tenantCode
      }, { $inc: { useCount: -materialCount } });
    });
    _.map(prods, (item) => {
      const { materials } = item;
      _.map(materials, async (it, k) => {
        const { usedProcureMaterialLots } = it;
        _.map(usedProcureMaterialLots, async (it, k) => {
          const { materialCount, pmLotId } = it;
          console.log('mm2', it);
          const res1 = await ctx.app.dbs.updateOne('ProcureMaterialRecord', {
            pmLotId,
            tenantCode
          }, { $inc: { useCount: materialCount } });
        });
      });
    });
  }

  async updateOne(body) {
    console.log('updateee', body);
    const res = await this.deleteOne(body);
    const result = await this.create(body);

    return { status: 'ok', result };
  }

  async deleteOne(body) {
    const { tenantCode, code, tenantName, createUser, createUsername, createdTs } = body;
    const { ctx } = this;
    const order = await ctx.app.dbs.findOne(table, { tenantCode, code });
    if (!order) {
      throw new Error('订单已删除');
    }
    if (order.reviewStatus === '同意') {
      throw new Error('删除失败！订单已审核通过！');
    }
    const lots = await ctx.app.dbs.find('OutboundLot', { orderCode: code, tenantCode });
    if (lots && lots.length > 0) {
      throw new Error('删除失败！订单已有发货记录，请删除发货记录后再执行订单删除！');
    }
    const { prods } = order;
    const res1 = await this.deleteSalesProds(ctx, tenantCode, prods);
    const result = await ctx.app.dbs.deleteOne(table, { tenantCode, code });
    const res = await ctx.app.dbs.deleteMany('SalesProdRecord', { tenantCode, salesOrderCode: code });
    const result1 = await ctx.app.dbs.deleteOne('History', { tenantCode, code });
    const result2 = await ctx.app.dbs.deleteOne('OutboundOrder', { tenantCode, salesOrderCode: code });
    const result3 = await ctx.app.dbs.deleteOne('OutboundLot', { tenantCode, salesOrderCode: code });
    const history = {
      table,
      name: '删除订单',
      oldData: order,
      tenantCode,
      code,
      tenantName,
      createUser,
      createUsername,
      createdTs
    };
    const historyRes = await ctx.app.dbs.insert('History', history);
    return { status: 'ok', result };
  }

  /**
   * 删除订单中的商品，包括物料占用
   * @returns {Promise<void>}
   * @param ctx
   * @param tenantCode
   * @param prods
   */
  async deleteSalesProds(ctx, tenantCode, prods) {

    _.map(prods, async prod => {
      const { materials } = prod;
      _.map(materials, async material => {
        const { usedMaterialRecord = [] } = material;
        _.map(usedMaterialRecord, async item => {
          const { _useCount = 0, pmLotId, } = item;
          if (_useCount > 0) {
            console.log('delete sales prods', _useCount);
            const res1 = await ctx.app.dbs.updateOne('ProcureMaterialRecord', {
              pmLotId,
              tenantCode
            }, { $inc: { useCount: -_useCount } });
          }
        });
      });
    });
  }

  /**
   * 创建订单商品，包括物料占用
   * @param ctx
   * @param tenantCode
   * @param code
   * @param prods
   * @returns {Promise<void>}
   */
  async createSalesProds(ctx, tenantCode, code, prods) {
    console.log('createSalesProds', prods.length);
    _.map(prods, async prod => {
      const { materials = [], laborFee } = prod;
      prod.salesOrderCode = code;
      prod.tenantCode = tenantCode;
      const result = await ctx.app.dbs.insert('SalesProdRecord', prod);
      console.log('materials', materials.length);
      _.map(materials, async material => {
        const { usedProcureMaterialLots = [] } = material;

        _.map(usedProcureMaterialLots, async item => {
          const { usedCount = 0, code, pmLotId, } = item;
          console.log('usedCount', usedCount);
          if (usedCount > 0) {
            console.log('updateOne sales ProcureMaterialRecord', usedCount);
            const res1 = await ctx.app.dbs.updateOne('ProcureMaterialRecord', { pmLotId }, { $inc: { useCount: usedCount } });

            const store = await ctx.app.dbs.findOne('Material', { code, tenantCode });
            if (store) {
              const { storeCount = 0 } = store;
              const c = storeCount - usedCount;
              const res = await ctx.app.dbs.updateOne('Material', { code, tenantCode }, { storeCount: c });
            }
          }
        });
      });
    });
  }

  async payReview(body) {
    const { ctx, service } = this;
    const { tenantCode, code } = body;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, body);
    return { status: 'ok', result };
  }

  async review(body) {
    const { ctx, service } = this;
    const { tenantCode, code, reviewStatus, createUser, createUsername, createdTs } = body;
    console.log('reviewStatus', body);
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, { reviewStatus });
    const order = await ctx.app.dbs.findOne(table, { tenantCode, code });
    const { tenantName } = order;
    const history = {
      table,
      name: '审核订单' + reviewStatus,
      oldData: order,
      tenantCode,
      code,
      tenantName,
      createUser,
      createUsername,
      createdTs
    };
    const historyRes = await ctx.app.dbs.insert('History', history);
    if (reviewStatus === '驳回') {
      const res = await service['outboundService'].deleteOne({ tenantCode, salesOrderCode: code });
      return { status: 'ok', result };
    }


    /**
     * 创建入库单
     */
    order.salesOrderCode = code;
    delete order['_id'];
    const result1 = await service['outboundService'].createOutboundOrder(order);
    return { status: 'ok', result };
  }

  async history(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.find('History', { table: 'SalesOrder', tenantCode, code });
    return { status: 'ok', result };
  }

  async exportExcel(body) {
    const { ctx } = this;
    const res = await this.findMany(body);
    const { result } = res;
    const mod = ctx.model['SalesOrder'];
    const _header = mod.schema.obj;
    delete _header['tenantName'];
    delete _header['tenantCode'];
    delete _header['createUser'];
    delete _header['createUsername'];
    delete _header['isDeleted'];
    delete _header['isEnabled'];
    delete _header['materialBody'];
    delete _header['labels'];
    delete _header['outboundCodes'];
    delete _header['outboundTime'];

    const header = [];
    _.map(_header, (item, key) => {
      item.title = item.desc;
      item.dataIndex = key;
      item.key = key;
      header.push(item);
    });
    console.log('excell', result);
    return { status: 'ok', result: { header, data: result } };
  }

  async uploadExcel(body) {
    const { ctx } = this;
    let { tenantCode, excelJson, table, createUser, createUsername, tenantName } = body;
    // console.log('bodyy', body);
    const modelStr = table.charAt(0)
      .toUpperCase() + table.slice(1);
    const mod = ctx.model[modelStr];
    const schema = mod.schema.obj;
    const _model = {};
    _.map(schema, (item, key) => {
      const { desc } = item;
      _model[desc] = key;
    });

    _.map(excelJson, async json => {
      const data = {};
      _.map(schema, async (item, key) => {
        const { desc, inputType } = item;
        data[key] = json[desc];
        if (inputType === 'switch') {
          data[key] = json[desc] === '是';
        }
        if (key === 'customerCode') {
          const customer = await ctx.app.dbs.findOne('Customer', { name: json['客户'] });
          data[key] = customer ? customer.code : data[key];
        }
      });

      // _.map(_model, (value, key) => {
      //   data[value] = item[key];
      // });
      const code = _stringUtils.getCode('SAL');
      data.code = code;
      data.tenantCode = tenantCode;
      data.createUser = createUser;
      data.createUsername = createUsername;
      data.tenantName = tenantName;
      data.reviewStatus = '待审核';
      data.createType = '导入';

      const res = await ctx.app.dbs.insert(modelStr, data);
      const history = {
        table,
        name: '导入订单',
        oldData: data,
        tenantCode,
        code,
        tenantName,
        createUser,
        createUsername,
      };
      const historyRes = await ctx.app.dbs.insert('History', history);
    });

    return { status: 'ok' };
  }

  async findStatisticsMany(body) {
    const { ctx } = this;
    let { tenantCode, customerCode, division } = body;
    // const users = await ctx.app.dbs.aggregate('User', [
    //   { $match: { ...body } },
    //   { $sort: { ...sort } },
    //   { $skip: skip },
    //   { $limit: limit },
    // ]);
    const result = [];
    const query = [ {
      $group: {
        '_id': { customer: '$customer', customerCode: '$customerCode', division: '$division' },
        list: { $push: '$$ROOT' }
      }
    } ];

    const res = await ctx.app.dbs.aggregate('SalesOrder', query);

    _.map(res, (item, key) => {
      const { _id, list } = item;
      let _invoiceAmount = 0,
        _amount = 0,
        _outboundAmount = 0;
      _.map(list, (item, key) => {
        const { prods, amount = 0, outboundAmount = 0 } = item;
        _amount += amount;
        _outboundAmount += outboundAmount;
        _.map(prods, (prod) => {
          const { price = 0, outboundCount = 0, invoicingDate, count } = prod;
          if (invoicingDate) {
            _invoiceAmount += price * count;
          }

        });
      });

      _id.outboundAmount = _outboundAmount;
      _id.amount = _amount;
      _id.invoiceAmount = _invoiceAmount;
      result.push(_id);
    });

    const res1 = await ctx.app.dbs.aggregate('Receipt', [ {
      $group: {
        '_id': { _accountName: '$_accountName', customer: '$customer' },
        list: { $push: '$$ROOT' }
      }
    } ]);
    _.map(res1, item => {
      const { _id, list } = item;
      let _receiptPayment = 0;
      _.map(list, (it, key) => {
        const { receiptAmount = 0 } = it;
        _receiptPayment += receiptAmount;
      });

      const { _accountName, customer } = _id;
      const temp = _.find(result, it => {
        return it.customer === customer && it.division === _accountName;
      });
      console.log('tempd', temp);
      if (temp) temp.receiptAmount = _receiptPayment;
    });

    return { status: 'ok', result };
  }

  /**
   * 退补货
   */
  async findReturnGoodsOrderMany(body) {
    const { ctx } = this;
    const { key, customer, prodCode, prodName, tenantCode, salesOrderCode, createdTs } = body;

    const query = { tenantCode };
    const _key = key ? key : 'createdTs';
    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const sort = {};
    sort[_key] = -1;

    if (customer) query['customer'] = { $regex: customer };
    if (prodCode) query['prodCode'] = { $regex: prodCode };
    if (prodName) query['prodName'] = { $regex: prodName };
    if (salesOrderCode) query['salesOrderCode'] = { $regex: salesOrderCode };

    const list = await ctx.app.dbs.find('SalesReturnGoodsOrder', query);
    const countRes = await this.app.dbs.aggregate('SalesReturnGoodsOrder', [
      { $match: { ...query } },
      { $group: { _id: null, count: { $sum: '$returnCount' } } },

    ]);
    const assessRes = await this.app.dbs.aggregate('SalesReturnGoodsOrder', [
      { $match: { ...query } },
      {
        $project: {
          totalPrice: { $multiply: [ '$returnCount', '$price' ] }
        }
      },
      {
        $group: {
          _id: null, // 使用null表示不需要分组，直接累加所有文档
          amount: { $sum: '$totalPrice' } // 对totalPrice字段进行累加
        }
      }
    ]);
    const count = countRes.length > 0 ? countRes[0].count : 0;
    const amount = assessRes.length > 0 ? assessRes[0].amount : 0;
    console.log('assess res', assessRes);
    return { status: 'ok', result: { list, count, amount } };
  }

  async deleteReturnGoodsOrder(body) {
    const { tenantCode, orderCode } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.deleteOne('SalesReturnGoodsOrder', { tenantCode, orderCode });
    // console.log('find sales order body', body);
    // result.prods = await ctx.app.dbs.find('ProdSalesRecord', { tenantCode, salesOrderCode: code });
    console.log('查找 订单', result);
    return { status: 'ok', result };
  }

  async createReturnGoodsOrder(body) {
    const { ctx } = this;
    delete body['_id'];
    const result = await ctx.app.dbs.insert('SalesReturnGoodsOrder', body);
    return { status: 'ok', result };
  }

  async updateReturnGoodsOrder(body) {
    const { tenantCode, orderCode, returnCount } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.updateOne('SalesReturnGoodsOrder', { tenantCode, orderCode }, { returnCount });
    return { status: 'ok', result };
  }

  async findReturnGoodsOrder(body) {
    const { tenantCode, orderCode, returnCount } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.findOne('SalesReturnGoodsOrder', { tenantCode, orderCode });
    return { status: 'ok', result };
  }

  async findReplenishRecordMany(body) {
    const { ctx } = this;
    const { key, customer, prodCode, prodName, tenantCode, salesOrderCode, createdTs } = body;
    const query = { tenantCode };
    const _key = key ? key : 'createdTs';
    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const sort = {};
    sort[_key] = -1;

    if (customer) query['customer'] = { $regex: customer };
    if (prodCode) query['prodCode'] = { $regex: prodCode };
    if (prodName) query['prodName'] = { $regex: prodName };
    if (salesOrderCode) query['salesOrderCode'] = { $regex: salesOrderCode };

    const list = await ctx.app.dbs.find('SalesReplenishRecord', query);
    const countRes = await this.app.dbs.aggregate('SalesReplenishRecord', [
      { $match: { ...query } },
      { $group: { _id: null, count: { $sum: '$count' } } },

    ]);
    const assessRes = await this.app.dbs.aggregate('SalesReplenishRecord', [
      { $match: { ...query } },
      {
        $project: {
          totalPrice: { $multiply: [ '$count', '$price' ] }
        }
      },
      {
        $group: {
          _id: null, // 使用null表示不需要分组，直接累加所有文档
          amount: { $sum: '$totalPrice' } // 对totalPrice字段进行累加
        }
      }
    ]);
    const count = countRes.length > 0 ? countRes[0].count : 0;
    const amount = assessRes.length > 0 ? assessRes[0].amount : 0;
    console.log('assess res', assessRes);
    return { status: 'ok', result: { list, count, amount } };
  }

  async deleteReplenishRecord(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.findOne(table, { tenantCode, code });
    // console.log('find sales order body', body);
    // result.prods = await ctx.app.dbs.find('ProdSalesRecord', { tenantCode, salesOrderCode: code });
    console.log('查找 订单', result);
    return { status: 'ok', result };
  }

  async createReplenishRecord(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.insert('SalesReplenishRecord', body);

    return { status: 'ok', result };
  }

  async updateReplenishRecord(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code });
    // console.log('find sales order body', body);
    // result.prods = await ctx.app.dbs.find('ProdSalesRecord', { tenantCode, salesOrderCode: code });
    console.log('查找 订单', result);
    return { status: 'ok', result };
  }

  async findReplenishRecord(body) {
    const { tenantCode, orderCode } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.findOne(table, { tenantCode, orderCode });
    return { status: 'ok', result };
  }

  async findSalesProdMany(body) {
    const { ctx } = this;
    const { key, customer, prodCode, prodName, salesOrderCode, tenantCode, createdTs } = body;
    const query = { tenantCode };
    const _key = key ? key : 'createdTs';
    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const sort = {};
    sort[_key] = -1;

    if (salesOrderCode) query['salesOrderCode'] = { $regex: salesOrderCode };
    if (customer) query['customer'] = { $regex: customer };
    if (prodCode) query['prodCode'] = { $regex: prodCode };
    if (prodName) query['prodName'] = { $regex: prodName };
    console.log('sssss', query);
    const result = await ctx.app.dbs.find('SalesProdRecord', query);
    console.log('sssss', result);
    return { status: 'ok', result };
  }
};
